package com.example.springsecurity.serivce;

import com.example.springsecurity.enums.ErrorCode;
import com.example.springsecurity.security.dto.LoginUserDto;
import com.example.springsecurity.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author wuancheng
 * @date 2024/6/21 10:07
 * @description
 */
@Component
public class TokenService {

    public final static String USER_KEY = "user:key:";

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 解析token
     *
     * @param token
     * @return
     */
    public LoginUserDto verifyToken(String token) {
        if (StringUtils.isBlank(token)){
            throw ErrorCode.PARAM_CANNOT_EMPTY.getMySecurityException("token");
        }
        String userId;
        try {
            userId = JwtUtil.parseJwtGetId(token);
        } catch (ExpiredJwtException e) {
            throw ErrorCode.TOKEN_EXPIRE_ERROR.getMySecurityException();
        } catch (Exception e) {
            throw ErrorCode.TOKEN_PARSE_ERROR.getMySecurityException();
        }
        LoginUserDto loginUserDto = (LoginUserDto) redisTemplate.opsForValue().get(USER_KEY + userId);
        if (loginUserDto == null) {
            throw ErrorCode.LOGIN_FAIL.getMySecurityException();
        }
        return loginUserDto;
    }

    /**
     * 生成token
     *
     * @param loginUserDto
     * @return
     */
    public String generateToken(LoginUserDto loginUserDto) {
        String userId = String.valueOf(loginUserDto.getId());
        String token = JwtUtil.createJwt(userId)[0];
        String key = USER_KEY + userId;
        redisTemplate.opsForValue().set(key, loginUserDto, JwtUtil.JWT_TTL, TimeUnit.SECONDS);
        return token;
    }
}
